package com.xxx.controller;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.apache.commons.lang3.math.NumberUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.xxx.common.Const;
import com.xxx.common.dto.JsonResult;
import com.xxx.common.dto.Pagination;
import com.xxx.common.dto.ZtreeNode;
import com.xxx.common.utils.ErrorUtil;
import com.xxx.model.SysMenu;
import com.xxx.model.SysRole;
import com.xxx.model.SysRoleMenu;
import com.xxx.service.SysMenuService;
import com.xxx.service.SysRoleMenuService;
import com.xxx.service.SysRoleService;

@Controller
@RequestMapping("sys/role/*")
public class SysRoleController {
	
	@Autowired
	private SysRoleService sysRoleService;
	
	@Autowired
	private SysRoleMenuService sysRoleMenuService; 
	
	@Autowired
	private SysMenuService sysMenuService;

	/**
	 * 列表 页面
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "index.html", method = RequestMethod.GET)
	public ModelAndView index(HttpServletRequest request) throws Exception{
		ModelAndView mv = new ModelAndView("sys/role/index");
		Map<String, Object> whereMap = new HashMap<>();
		List<SysRole> list = sysRoleService.getList(whereMap, new Pagination(1, Integer.MAX_VALUE, "orderno asc"));
		mv.addObject("list", list);
		return mv;
	}
	
	/**
	 * 添加/修改 页面
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "create.html", method = RequestMethod.GET)
	public ModelAndView create(HttpServletRequest request) throws Exception{
		ModelAndView mv = new ModelAndView("sys/role/create");
		long id = NumberUtils.toLong(request.getParameter("id"), Const.DEFAULT_LONG_NULL);
		if(id != Const.DEFAULT_LONG_NULL){
			SysRole sysRole = sysRoleService.getEntity(id);
			mv.addObject("data", sysRole);
		}
		mv.addObject("statuslist", Const.getStatusList("停用","启用"));
		return mv;
	}
	
	/**
	 * 保存/修改
	 * @param SysRole
	 * @param result
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping(value = "save", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
	public JsonResult save(@Valid SysRole sysRole, BindingResult result) throws Exception {
		if (result.hasErrors()) {
			return ErrorUtil.getError(result);
		}
		long ret = sysRoleService.saveOrUpdate(sysRole);
		if(ret > 0){
			return JsonResult.ok();
		}
		return JsonResult.build(-1, "保存失败!");
	}
	
	/**
	 * 删除
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping(value = "delete", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
	public JsonResult delete(HttpServletRequest request) throws Exception {
		String[] ids = request.getParameterValues("checkedid");
		if(ids == null || ids.length == 0){
			return JsonResult.build(-1, "请选择要删除的记录!");
		}
		for (String id : ids) {
			sysRoleService.delete(NumberUtils.toLong(id));
		}
		return JsonResult.ok();
	}
	
	/**
	 * 菜单授权 树
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping(value = "menu_grant.html",method = {RequestMethod.GET})
	public ModelAndView menuGrant(HttpServletRequest request) throws Exception{
		ModelAndView mv = new ModelAndView("sys/role/menu_grant");
		long roleid = NumberUtils.toLong(request.getParameter("roleid"), Const.DEFAULT_LONG_NULL);	//角色id
		if(roleid != Const.DEFAULT_LONG_NULL){
			Map<String, Object> whereMap = new HashMap<>();
			List<SysMenu> menuList = sysMenuService.getList(whereMap);
			Map<Long,Long> roleMenuMap = sysRoleMenuService.getRoleMenuMap(roleid);
			List<ZtreeNode> nodeList = new ArrayList<>();
			ZtreeNode node = null;
			for (SysMenu menu : menuList) {
				node = new ZtreeNode(menu.getId().toString(), menu.getParentid()+"", menu.getMenuname(), roleMenuMap.containsKey(menu.getId()));
				nodeList.add(node);
			}
			mv.addObject("nodelist", JSON.toJSONString(nodeList));
			mv.addObject("roleid", roleid);
		}
		return mv;
	}
	
	/**
	 * 菜单授权保存
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping(value = "menu_grant_save", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
	public JsonResult menuGrantSave(HttpServletRequest request) throws Exception {
		long roleid = NumberUtils.toLong(request.getParameter("roleid"), Const.DEFAULT_LONG_NULL);	//角色id
		String[] ids = request.getParameterValues("ids[]");
		Map<Long,Long> roleMenuMap = sysRoleMenuService.getRoleMenuMap(roleid);
		if(ids != null){
			SysRoleMenu roleMenu = null;
			for (String strid : ids) {
				long menuid = NumberUtils.toLong(strid);
				if(roleMenuMap.containsKey(menuid)){
					roleMenuMap.remove(menuid);
				}else{
					roleMenu = new SysRoleMenu(roleid, menuid);
					sysRoleMenuService.saveOrUpdate(roleMenu);	 //添加授权
				}
			}
		}
		if(!roleMenuMap.isEmpty()){
			for (Long id : roleMenuMap.values()) {
				sysRoleMenuService.delete(id);					 //取消授权
			}
		}
		return JsonResult.ok();
	}
}
